package com.xuecheng.order.task;

import com.xuecheng.framework.domain.task.XcTask;
import com.xuecheng.order.config.RabbitMQConfig;
import com.xuecheng.order.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * @author zhaoxiang
 * @version 1.0
 * @Date 2020/2/26 20:15
 */
@Component
public class ChooseCourseTask {

    private static final Logger logger = LoggerFactory.getLogger(ChooseCourseTask.class);

    @Autowired
    private TaskService taskService;

    /**
     * 获取当前时间前n分钟
     * @param
     * @return
     */
    @Scheduled(cron = "0/10 * * * * *")
    public void sendChooseCourseTask(){
        //取出当前时间3分钟之前的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar =new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(GregorianCalendar.MINUTE,-3);
        Date time = calendar.getTime();
        List<XcTask> taskList = taskService.findTaskList(time, 1000);
//        String format = sdf.format(time);
//        System.out.println(format);
        //调用service将添加选课信息发送给mq
        for(XcTask xcTask : taskList){
            int count = taskService.getTask(xcTask.getId(), xcTask.getVersion());
            if(count > 0){
                String mqExchange = xcTask.getMqExchange();//要发送的交换机
                String mqRoutingkey = xcTask.getMqRoutingkey();//发送消息需要携带的routingKey
                taskService.publish(xcTask, mqExchange, mqRoutingkey);
                logger.info("send  choose course task id:{}", xcTask.getId());
            }
        }
    }

    /**
     * 接收选课响应结果
     *
     * @param xcTask
     */
    @RabbitListener(queues = {RabbitMQConfig.XC_LEARNING_FINISHADDCHOOSECOURSE})
    public void receiveFinishChooseCourseTask(XcTask xcTask){
        if (xcTask != null && StringUtils.isNotEmpty(xcTask.getId())){
            logger.info("receiveChooseCourseTask...{}",xcTask.getId());
            //接收到 的消息id
            String id = xcTask.getId();
            //删除任务，添加历史任务
            taskService.finishTask(id);
        }
    }

//    @Scheduled(cron = "0/3 * * * * *")
    public void test1(){
        try {
            logger.info("===================test1任务开始==================");
            Thread.sleep(5000);
            logger.info("===================test1任务结束==================");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
